#!/usr/bin/env bash
set -euo pipefail

NTH_HELM_DIR=config/helm/aws-node-termination-handler

function version { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; }

EXIT_CODE=0
# Helm yaml changes should increment Chart version EXCEPT FOR test.yaml
HELM_FILES_CHANGED=$(git show --name-only | grep -E "$NTH_HELM_DIR" | grep .yaml | grep -v test.yaml || :)
if [[ -z $HELM_FILES_CHANGED ]]; then
  echo "✅ No Helm file changes detected"
  exit $EXIT_CODE
fi

echo "📝 Helm chart changes detected! Checking for updated Chart versions since the last release"
LATEST_COMMIT_HASH=$(git rev-parse HEAD)
LATEST_COMMIT_CHART_VERSION=$(git --no-pager show "$LATEST_COMMIT_HASH":"$NTH_HELM_DIR"/Chart.yaml | grep 'version:' | xargs | cut -d' ' -f2 | tr -d '[:space:]')

TAG=$(git describe HEAD --tags | grep -Eo "^v[0-9]+(\.[0-9]+)*")
LAST_RELEASE_HASH=$(git rev-list -1 "$TAG")
LAST_RELEASE_CHART_VERSION=$(git --no-pager show "$LAST_RELEASE_HASH":"$NTH_HELM_DIR"/Chart.yaml | grep 'version:' | xargs | cut -d' ' -f2 | tr -d '[:space:]')
if [[ $LAST_RELEASE_CHART_VERSION == "$LATEST_COMMIT_CHART_VERSION" ]]; then
  echo "❌ This commit's NTH Chart has the same Chart version as the latest release $LATEST_COMMIT_CHART_VERSION -- please increment Chart version in NTH"
  EXIT_CODE=1
elif [[ $(version $LATEST_COMMIT_CHART_VERSION) -lt $(version $LAST_RELEASE_CHART_VERSION) ]]; then
  echo "❌ This commit's NTH Chart version $LATEST_COMMIT_CHART_VERSION is BEHIND the latest release's chart version $LAST_RELEASE_CHART_VERSION -- please increment Chart version in NTH"
  EXIT_CODE=1
else
  echo "✅ This commit's NTH Chart has a different version since the last release ($LAST_RELEASE_CHART_VERSION -> $LATEST_COMMIT_CHART_VERSION)"
fi

exit $EXIT_CODE